package com.free4inno.knowledgems.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.free4inno.knowledgems.dao.AttachmentDAO;
import com.free4inno.knowledgems.dao.ResourceDAO;
import com.free4inno.knowledgems.dao.SystemManageDAO;
import com.free4inno.knowledgems.dao.TemplateDAO;
import com.free4inno.knowledgems.domain.Attachment;
import com.free4inno.knowledgems.domain.GroupInfo;
import com.free4inno.knowledgems.domain.Resource;
import com.free4inno.knowledgems.domain.Template;
import com.free4inno.knowledgems.service.LabelService;
import com.free4inno.knowledgems.service.ResourceEsService;
import com.free4inno.knowledgems.service.ResourceService;
import com.free4inno.knowledgems.service.UserService;
import com.free4inno.knowledgems.constants.UserConstants;
import com.free4inno.knowledgems.utils.ImageUtils;
import com.free4inno.knowledgems.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.sql.Timestamp;
import java.util.*;

/**
 * Author HaoYi.
 * Date 2020/9/16.
 */

@Slf4j
@Controller
@RequestMapping("crudres")
public class CrudResController {

    @Autowired
    private ResourceDAO resourceDao;

    @Autowired
    private AttachmentDAO attachmentDao;

    @Autowired
    private TemplateDAO templateDao;

    @Autowired
    private LabelService labelService;

    @Autowired
    private UserService userService;

    @Autowired
    private ResourceEsService esService;

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private SystemManageDAO systemManageDao;

    @Autowired
    private ImageUtils imageUtils;

    @RequestMapping("new")
    public String newApp(HttpSession session, Map param) {
        log.info(this.getClass().getName() + "----in----" + "新建(new)" + "----" + session.getAttribute(UserConstants.USER_ID));
        // get groupList
        Integer userId = Integer.parseInt(session.getAttribute(UserConstants.USER_ID).toString());
        Boolean isSuperUser = userService.isSuperUser(userId.toString());
        Boolean isContentUser = userService.isContentUser(userId.toString());
        List<GroupInfo> groupInfoList = userService.userGroupInfosAll(userId);

        param.put("user_id",session.getAttribute(UserConstants.USER_ID));
        param.put("isSuperUser", isSuperUser);
        param.put("isContentUser", isContentUser);
        param.put("groupInfoList", groupInfoList);
        // get templateList
        List<Template> templateInfoList = templateDao.findAll();
        param.put("templateInfoList", templateInfoList);
        // get book label id
        String bookLabelId = systemManageDao.findAllByVariable("book_label").get().getValue();
        param.put("bookLabelId", bookLabelId);
        log.info(this.getClass().getName() + "----out----" + "跳转到新建页面" + "----" + session.getAttribute(UserConstants.USER_ID));
        return "crud/newres";
    }

    @ResponseBody
    @GetMapping("getTemplateCode")
    public Map<String, Object> getTemplateCode(@RequestParam("id") Integer id, HttpSession session) {
        log.info(this.getClass().getName() + "----in----" + "获取模板编码(getTemplateCode)" + "----" + session.getAttribute(UserConstants.USER_ID));
        Map<String, Object> jsonObject = new HashMap<>();
        String templateCode = templateDao.findById(id).get().getTemplateCode();
        jsonObject.put("templateCode", templateCode);
        jsonObject.put("code", 200);
        jsonObject.put("msg", "OK");
        log.info(this.getClass().getName() + "----out----" + "返回获取到的模板编码" + "----" + session.getAttribute(UserConstants.USER_ID));
        return jsonObject;
    }

    @ResponseBody
    @GetMapping("getLabel")
    public Map<String, Object> getLabels(HttpSession session) {
        log.info(this.getClass().getName() + "----in----" + "获取标签(getLabel)" + "----" + session.getAttribute(UserConstants.USER_ID));
        Map<String, Object> jsonObject = new HashMap<>();
        List<List<Map<String, String>>> tagList = labelService.getLabels();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "OK");
        jsonObject.put("result", tagList);
        log.info(this.getClass().getName() + "----out----" + "返回获取到的标签列表" + "----" + session.getAttribute(UserConstants.USER_ID));
        return jsonObject;
    }

    @RequestMapping("newdata")
    @ResponseBody
    public Map<String, Object> newResource(@RequestParam("title") String title,
                                           @RequestParam("group") String group,
                                           @RequestParam("label") String label,
                                           @RequestParam("text") String text,
                                           @RequestParam("attachment") String attachmentJson,
                                           @RequestParam("superior") Integer superior,
                                           @RequestParam("contents") String contents,
                                           HttpSession session,
                                           HttpServletRequest request) throws Exception {
        log.info(this.getClass().getName() + "----in----" + "保存新建资源(newdata)" + "----" + session.getAttribute(UserConstants.USER_ID));
        Map<String, Object> jsonObject = new HashMap<>();
        if (title.equals("") || text.equals("")) {
            jsonObject.put("msg", "必填项未填写完整");
            log.info(this.getClass().getName() + "----out----" + "保存新建资源失败(必填项未填写完整)" + "----" + session.getAttribute(UserConstants.USER_ID));
            return jsonObject;
        }
        text = imageUtils.DownloadExternalImage(text, session); //调用ImageUtils下载外链图片的方法
        Integer userId = (Integer) session.getAttribute(UserConstants.USER_ID);
        Resource resource = new Resource();
        resource.setUserId(userId);
        resource.setCreateTime(new Timestamp(new Date().getTime()));
        resource.setEditTime(new Timestamp(new Date().getTime()));
        resource.setTitle(title);
        resource.setText(text);
        resource.setPermissionId(0); //默认为不公开资源
        resource.setSuperior(superior);
        resource.setGroupId(group);
        resource.setLabelId(label);
        resource.setContents(contents);
        Integer id = resourceDao.saveAndFlush(resource).getId();
        esService.addResourceES(resource.getId());

        //保存附件信息
        JSONArray attachmentJsonArray = JSON.parseArray(attachmentJson);
        String temp_msg = null;
        if (attachmentJsonArray.size() > 0) temp_msg = attachmentJsonArray.getJSONObject(0).getString("temp_msg");
        if (temp_msg != null) {
            log.info(this.getClass().getName() + "----" + "自动保存，无需改变附件信息" + "----" + session.getAttribute(UserConstants.USER_ID));
        } else {
            // 不是临时保存，更新附件信息
            log.info(this.getClass().getName() + "----" + "保存附件信息" + "----" + session.getAttribute(UserConstants.USER_ID));
            for (int i = 0; i < attachmentJsonArray.size(); i++) {
                JSONObject attachmentJsonObject = attachmentJsonArray.getJSONObject(i);
                Optional<Attachment> attachmentOptional = attachmentDao.findById(attachmentJsonObject.getInteger("attachmentId"));
                if (attachmentOptional.isPresent()) {
                    Attachment attachment = attachmentOptional.get();
                    // 更新数据项的内容
                    attachment.setResourceId(id);
                    attachmentDao.save(attachment);  // 更新数据项
                }
            }
        }
        jsonObject.put("msg", "SUCCESS");
        jsonObject.put("resourceId", resource.getId());
        log.info(this.getClass().getName() + "----out----" + "保存新建资源成功，返回资源id" + "----" + session.getAttribute(UserConstants.USER_ID));
        return jsonObject;
    }

    @RequestMapping("edit")
    public String editResource(@RequestParam("id") Integer id, HttpSession session, Map param) {
        log.info(this.getClass().getName() + "----in----" + "编辑(edit)" + "----" + session.getAttribute(UserConstants.USER_ID));

        Resource resource = resourceDao.findById(id).get();
//        System.out.print("初始数据："+resource.getText());
        resource.setTitle(StringUtils.inputStringFormat(resource.getTitle()));
        resource.setText(StringUtils.inputStringFormat(resource.getText()));
//        System.out.print("处理后数据："+resource.getText());

        Integer userId = Integer.parseInt(session.getAttribute(UserConstants.USER_ID).toString());
        Boolean isSuperUser = userService.isSuperUser(userId.toString());
        Boolean isContentUser = userService.isContentUser(userId.toString());
        List<GroupInfo> groupInfoList = userService.userGroupInfosAll(userId);

        param.put("user_id",session.getAttribute(UserConstants.USER_ID));
        param.put("isSuperUser", isSuperUser);
        param.put("isContentUser", isContentUser);
        param.put("groupInfoList", groupInfoList);
        param.put("resource", resource);
        //取资源的附件
        String attachment = resourceService.getAttachmentJson(id);
        param.put("attachment", attachment);
        // get templateList
        List<Template> templateInfoList = templateDao.findAll();
        param.put("templateInfoList", templateInfoList);
        // get book label id
        String bookLabelId = systemManageDao.findAllByVariable("book_label").get().getValue();
        param.put("bookLabelId", bookLabelId);
        log.info(this.getClass().getName() + "----out----" + "跳转到编辑资源页面" + "----" + session.getAttribute(UserConstants.USER_ID));
        return "crud/editres";
    }

    @RequestMapping("editdata")
    @ResponseBody
    public Map<String, Object> editdata(@RequestParam("id") Integer id,
                                        @RequestParam("title") String title,
                                        @RequestParam("group") String group,
                                        @RequestParam("label") String label,
                                        @RequestParam("text") String text,
                                        @RequestParam("attachment") String attachmentJson,
                                        @RequestParam("superior") Integer superior,
                                        @RequestParam("contents") String contents,
                                        HttpSession session,
                                        HttpServletRequest request) throws Exception {
        log.info(this.getClass().getName() + "----in----" + "保存编辑资源(editdata)" + "----" + session.getAttribute(UserConstants.USER_ID));
        Map<String, Object> jsonObject = new HashMap<>();
        if (id == null) {
            log.info(this.getClass().getName() + "----out----" + "保存编辑资源失败，资源id参数为null" + "----" + session.getAttribute(UserConstants.USER_ID));
            return jsonObject;
        }
        Resource resource = resourceDao.findById(id).get();
        if (title.equals("") || text.equals("")) {
            jsonObject.put("msg", "必填项未填写完整");
            log.info(this.getClass().getName() + "----out----" + "保存编辑资源失败(必填项未填写完整)" + "----" + session.getAttribute(UserConstants.USER_ID));
            return jsonObject;
        }
        text = imageUtils.DownloadExternalImage(text, session); //调用ImageUtils下载外链图片的方法
        //System.out.print(imageSrc);
        resource.setTitle(title);
        resource.setText(text);
        resource.setGroupId(group);
        resource.setEditTime(new Timestamp(new Date().getTime()));
        resource.setLabelId(label);
        resource.setSuperior(superior);
        resource.setContents(contents);
        resourceDao.saveAndFlush(resource);
        esService.updateResourceES(resource.getId());

        //保存附件信息
        JSONArray attachmentJsonArray = JSON.parseArray(attachmentJson);
        String temp_msg = null;
        if (attachmentJsonArray.size() > 0) temp_msg = attachmentJsonArray.getJSONObject(0).getString("temp_msg");
        if (temp_msg != null) {
            log.info(this.getClass().getName() + "----" + "自动保存，无需改变附件信息" + "----" + session.getAttribute(UserConstants.USER_ID));
        } else {
            log.info(this.getClass().getName() + "----" + "保存附件信息" + "----" + session.getAttribute(UserConstants.USER_ID));
            // 不是临时保存，更新附件信息
            for (int i = 0; i < attachmentJsonArray.size(); i++) {
                JSONObject attachmentJsonObject = attachmentJsonArray.getJSONObject(i);
                Optional<Attachment> attachmentOptional = attachmentDao.findById(attachmentJsonObject.getInteger("attachmentId"));
                if (attachmentOptional.isPresent()) {
                    Attachment attachment = attachmentOptional.get();
                    // 更新附件resourceId的内容
                    attachment.setResourceId(id);
                    attachmentDao.save(attachment);  // 更新数据项
                }
            }
        }
        jsonObject.put("msg", "SUCCESS");
        log.info(this.getClass().getName() + "----out----" + "保存编辑资源成功，返回成功json" + "----" + session.getAttribute(UserConstants.USER_ID));
        return jsonObject;
    }
}
